import { defineStore } from 'pinia'
import request, { getServerUrl } from '../utils/request';

export const useUserStore = defineStore('user', {
  state: () => {
    // 尝试从本地存储恢复用户信息
    const storedUser = localStorage.getItem('user');
    const initialUser = storedUser ? JSON.parse(storedUser) : null;
    
    return {
      user: initialUser,
      isAuthenticated: !!initialUser,
    }
  },
  getters: {
    getUser: (state) => {
      return state.user
    },
    isLoggedIn: (state) => {
      return state.isAuthenticated
    }
  },
  actions: {
    setUser(userData) {
      this.user = userData;
      this.isAuthenticated = true;
      
      // 处理头像URL，确保是完整URL
      if (this.user && this.user.avatarUrl && !this.user.avatarUrl.startsWith('http')) {
        // 如果不是完整URL，拼接服务器地址
        if (!this.user.avatarUrl.startsWith('/')) {
          this.user.avatarUrl = '/' + this.user.avatarUrl;
        }
      }
      
      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify(this.user));
    },
    logout() {
      this.user = null;
      this.isAuthenticated = false;
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    },
    async checkAndRefreshAuth() {
      const token = localStorage.getItem('token');
      if (!token) {
        this.logout();
        return false;
      }
      
      try {
        // 这里可以添加token验证逻辑
        // 如果token无效，返回false
        return true;
      } catch (error) {
        console.error('认证校验失败:', error);
        this.logout();
        return false;
      }
    }
  }
})
